import axios from 'axios'
import Utils from './utils'
import JsonP from 'jsonp';
export default class Axios {

    //请求方法

    static requestList(_this, url, methods,params, obj = {}) {
        if(_this.mounted) {
            _this.setState({
                selectedRowKeys: [],
                loading: true
            }, () => {
                Axios.ajax({
                    url: url,
                    methods: methods,
                    params: Object.assign(params, obj)
                }).then((res) => {
                    _this.setState({
                        loading: false
                    }, () => {
                        if(res.code === '000000'){
                            res.data.map((item, index) => {
                                return item.key = index;
                            })
                            _this.setState({
                                data: res.data,
                                totalRecord: res.totalRecord,
                                pagination: Utils.pagination(res,(current)=>{
                                    _this.params.page = current;
                                    if(Object.keys(_this.params.cityInfo).length) {
                                        _this.getUserList(_this.params.cityInfo);
                                    } else {
                                        _this.getUserList();
                                    }
                                })
                            })
                        }
                    })
                })
            })
        } 

    }
    static jsonp(options) {
        return new Promise((resolve, reject) => {
            JsonP(options.url, {
                param: 'callback'
            },function(err, response) {
                if(response.status === 'success') {
                    resolve(response)
                } else {
                    reject(response.message)
                }
            })
        })
    }

    static ajax(options){
        let data = options.methods.toLocaleLowerCase() === 'get' ? 'params' : 'data',
            token = window.sessionStorage.getItem('token');
        return new Promise((resolve,reject)=>{
            axios({
                url:options.url,
                method: options.methods,
                timeout:5000,
                [data]: options.params || '',
                headers: {
                    'token': token
                }
            }).then((res)=>{
                if (res.status === 200) {
                    resolve(res.data)
                } else {
                    reject(res.data)
                }
            }).catch((err) => {
                reject(err);
            })
        });
    }
}